#include "testwidget.h"
#include <QVBoxLayout>
#include <QGraphicsView>
#include <QInputDialog>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>

testWidget::testWidget(QWidget *parent)
    : QWidget{parent}
{
    m_map = new myMap(myMap::InnerType, "InnerMap.json");

    // 创建布局和视图
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    scene = new CustomScene();

    view = new CustomGraphicsView();
    view->setScene(scene);
    view->setRenderHint(QPainter::Antialiasing);
    view->setSceneRect(0, 0, 800, 600);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    layout->addWidget(view);
    resize(800, 600);

    // 连接信号槽
    connect(scene, &CustomScene::nodeClicked, this, &testWidget::handleNodeClicked);
    connect(scene, &CustomScene::nodesConnected, this, &testWidget::handleNodesConnected);
    for (auto &item : m_map->getAllNodeInfo()) {
        QString str = QString::fromStdString(item.second.getName());
        QPointF pos(item.second.getX(), item.second.getY());
        NodeItem *newNode = new NodeItem(str, pos, nodeNum);
        scene->addItem(newNode);
        ++nodeNum;
    }
}

testWidget::~testWidget() {
    delete m_map;
}
void testWidget::handleNodeClicked(NodeItem* node, QPointF pos)
{
    if (!node) {
        // 原有创建节点逻辑
        bool ok;
        QString name = QInputDialog::getText(this,
                                             tr("节点名称"),
                                             tr("请输入节点名称:"),
                                             QLineEdit::Normal,
                                             "",
                                             &ok);
        if (ok && !name.isEmpty()) {
            NodeItem* newNode = new NodeItem(name, pos, nodeNum);
            scene->addItem(newNode);
            myNode *n = new myNode;
            std::string str = name.toStdString();
            n->init(nodeNum, str, pos.x(), pos.y());
            ++nodeNum;
            m_map->addNode(n);
        }
    }
}

void testWidget::handleNodesConnected(NodeItem *start, NodeItem *end)
{
    // 创建连线
    LineItem* connection = new LineItem(start, end);
    scene->addItem(connection);

    // 为两个节点添加连接引用
    start->addConnection(connection);
    end->addConnection(connection);
    if (start->getID() < end->getID()) {
        m_map->addAdjNode(start->getID(), end->getID());
    } else {
        m_map->addAdjNode(end->getID(), start->getID());
    }

    // 更新连线位置
    connection->updatePosition();
}

// NodeItem实现
NodeItem::NodeItem(const QString &name, const QPointF &pos, const int ID)
    : m_name(name), m_ID(ID)
{
    setPos(pos);
    setFlags(QGraphicsItem::ItemIsSelectable);
}

QRectF NodeItem::boundingRect() const
{
    return QRectF(-5, -5, 10, 10); // 包含文本空间
}

void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    // 绘制圆形
    painter->setPen(Qt::black);
    painter->setBrush(Qt::lightGray);
    painter->drawEllipse(-5, -5, 10, 10);

    // 绘制文字
    painter->setPen(Qt::black);
    QFont font = painter->font();
    font.setPointSize(8);
    painter->setFont(font);
    painter->drawText(QRectF(-15, -10, 30, 20), Qt::AlignCenter, m_name);
}

// 修改CustomScene的鼠标事件处理
CustomScene::CustomScene(QObject *parent)
    : QGraphicsScene(parent){ }

void CustomScene::mousePressEvent(QGraphicsSceneMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        // 获取点击位置的节点
        QGraphicsItem* item = itemAt(event->scenePos(), QTransform());
        NodeItem* clickedNode = dynamic_cast<NodeItem*>(item);

        if (clickedNode) {
            if (!m_selectedNode) {
                // 首次选择节点
                m_selectedNode = clickedNode;
                m_selectedNode->setSelected(true);
            } else if (m_selectedNode != clickedNode) {
                // 连接两个不同节点
                emit nodesConnected(m_selectedNode, clickedNode);
                m_selectedNode->setSelected(false);
                m_selectedNode = nullptr;
            }
            emit nodeClicked(clickedNode, event->scenePos());
        } else {
            // 点击空白区域时清空选择
            if (m_selectedNode) {
                m_selectedNode->setSelected(false);
                m_selectedNode = nullptr;
            }
            emit nodeClicked(nullptr, event->scenePos());
        }
    }
    QGraphicsScene::mousePressEvent(event);
}

// LineItem实现
LineItem::LineItem(NodeItem* startNode, NodeItem* endNode, QGraphicsItem* parent)
    : QGraphicsLineItem(parent), m_startNode(startNode), m_endNode(endNode) {
    setPen(QPen(Qt::darkGray, 2));
    updatePosition();
}

void LineItem::updatePosition() {
    QLineF line(m_startNode->pos(), m_endNode->pos());
    setLine(line);
}

// NodeItem新增方法实现
void NodeItem::addConnection(LineItem* connection) {
    if (!m_connections.contains(connection)) {
        m_connections.append(connection);
    }
}
QList<NodeItem*> NodeItem::connectedNodes() const {
    QList<NodeItem*> nodes;
    foreach (LineItem* connection, m_connections) {
        if (connection->startNode() != this)
            nodes.append(connection->startNode());
        if (connection->endNode() != this)
            nodes.append(connection->endNode());
    }
    return nodes;
}

QPointF &NodeItem::getPos() {
    return m_pos;
}

int NodeItem::getID() const {
    return m_ID;
}
CustomGraphicsView::CustomGraphicsView(QWidget* parent)
    : QGraphicsView(parent) {
    // 启用抗锯齿和优化渲染
    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    // 设置缩放锚点为鼠标位置
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
}

void CustomGraphicsView::wheelEvent(QWheelEvent* event) {
    if (event->modifiers() & Qt::ControlModifier) {
        // 计算缩放因子（每步缩放5%）
        const double scaleFactor = 1.15;
        double zoom = 1.0;

        // 根据滚轮方向计算缩放
        if (event->angleDelta().y() > 0) {
            zoom = scaleFactor;
        } else {
            zoom = 1.0 / scaleFactor;
        }

        // 应用缩放并限制范围
        QTransform transform = this->transform();
        double currentScale = transform.m11();

        if ((zoom > 1 && currentScale < 10) ||
            (zoom < 1 && currentScale > 0.1)) {
            scale(zoom, zoom);
        }
    } else {
        // 非Ctrl键时保持默认滚动行为
        QGraphicsView::wheelEvent(event);
    }
}

void CustomGraphicsView::mousePressEvent(QMouseEvent* event) {
    // 记录鼠标位置（用于拖拽视图）
    m_lastMousePos = event->pos();
    QGraphicsView::mousePressEvent(event);
}
